//
//  NSObject+Tool.m
//  HX2Car
//
//  Created by Mudmen on 2020/3/6.
//  Copyright © 2020 Hx2car_mac. All rights reserved.
//

#import "NSObject+Tool.h"

@implementation NSObject (Tool)

#pragma mark - getCurrentVC
- (UIViewController *)getCurrentVC
{
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    LogInfo(@"rootViewController = %@",rootViewController);
    UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];
    LogInfo(@"currentVC = %@",currentVC);
    return currentVC;
}

- (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC
{
    UIViewController *currentVC;
    if ([rootVC presentedViewController]) {
        // 视图是被presented出来的
        rootVC = [rootVC presentedViewController];
    }
    if ([rootVC isKindOfClass:[UITabBarController class]]) {
        // 根视图为UITabBarController
        currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];
    } else if ([rootVC isKindOfClass:[UINavigationController class]]){
        // 根视图为UINavigationController
        currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];
    } else {
        // 根视图为非导航类
        currentVC = rootVC;
    }
    return currentVC;
}

@end
